let app = getApp()
Page({
  data: {
    url: '',
    reply: '',
    userId: 0,
    psychId: 0, // 问题ID
  },

  // 提交回复
  postReply() {
    if (!this.data.reply.trim()) {
      wx.showToast({ title: '回复内容不能为空', icon: 'none' });
      return;
    }

    wx.request({
      url: this.data.url + 'psychReply/add',
      method: 'POST',
      data: {
        replyContent: this.data.reply,
        userId: this.data.userId,
        replyTime: new Date().toISOString(),
        psychId: this.data.psychId
      },
      success: (resp) => {
        if (resp.data.code === 200) {
          wx.showToast({ title: '回复成功', icon: 'success' });
          this.incrementReplyCount(); // 调用更新评论数方法
        } else {
          wx.showToast({ title: '回复失败', icon: 'error' });
          setTimeout(() => wx.switchTab({ url: '/pages/home/home' }), 1500);
        }
      },
      fail: () => {
        wx.showToast({ title: '发送失败', icon: 'error' });
        setTimeout(() => wx.switchTab({ url: '/pages/home/home' }), 1500);
      }
    })
  },

  // 更新评论数
  incrementReplyCount() {
    const updateUrl = `${this.data.url}psych/updateReplyCount?psychId=${this.data.psychId}`;
    
    wx.request({
      url: updateUrl,
      method: 'PUT',
      success: (resp) => {
        wx.showToast({ 
          title: resp.data.code === 200 ? '评论数已更新' : '评论数更新失败',
          icon: resp.data.code === 200 ? 'success' : 'error'
        });

        // 返回上一页（延迟1.5秒，让用户看到提示）
        setTimeout(() => {
          wx.navigateBack({ delta: 1 });
        }, 1500);
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
        setTimeout(() => wx.navigateBack({ delta: 1 }), 1500);
      }
    })
  },

  // 页面加载
  onLoad(options) {
    const user = wx.getStorageSync('user');
    if (!user) {
      wx.showModal({
        title: '未登录',
        content: '请先登录',
        complete: (res) => {
          const url = res.confirm ? '/pages/login/login' : '/pages/home/home';
          res.confirm ? wx.navigateTo({ url }) : wx.switchTab({ url });
        }
      });
      return;
    }

    this.setData({
      url: app.globalData.url,
      userId: user.id,
      psychId: options.psychId
    });
  },

  // 其他生命周期（默认）
  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
})
